<template>
  <view v-show="data.name" class="detail-wrap">
    <view class="title">{{ data.name }}</view>

    <view class="time">{{ $u.timeFrom(data.time, "yyyy年mm月dd日") }}</view>

    <view class="creator">
      <img :src="data.creatorFile.avatarUrl" />
      <view class="creator-name">{{ data.creatorFile.nickName }}</view>
      <view class="join-btn">
        <u-button
          v-if="!joined"
          :ripple="true"
          type="primary"
          @click="joinActivity"
        >
          加入活动
        </u-button>
        <u-button
          v-else
          :ripple="true"
          type="error"
          @click="showQuitModal = true"
        >
          我要鸽了
        </u-button>
      </view>
    </view>

    <view class="user-list-tip">参与者</view>

    <view v-if="data.users && data.users.length" class="user-list">
      <view
        v-for="(item, index) in data.users"
        :key="item.id"
        class="user-item"
      >
        <view class="user-rank" v-if="!item.quit">{{ index + 1 }}</view>
        <view class="user-quit" v-else>🕊</view>
        <img :src="item.avatarUrl" class="user-avatar" />
        <view class="user-name">{{ item.nickName }}</view>
        <view :class="['user-score', item.score > 0 ? 'high' : 'low']">{{
          item.score
        }}</view>
        <view v-show="item.id === userInfo.id && !item.quit" class="socre-mod">
          <img
            class="mod-icon"
            src="/static/modify.png"
            @click="
              showMod = true;
              opIndex = index;
            "
          />
        </view>
      </view>
      <view class="counter">
        <view class="counter-item">Bonus: {{ bonus }}</view>
        <view class="counter-item">Offset: {{ offset }}</view>
      </view>
    </view>

    <view v-else class="empty-wrap">
      <u-empty text="还没人参加呢" />
    </view>

    <u-modal
      v-model="showMod"
      :show-title="false"
      confirm-color="#333"
      :content-style="{ padding: '30rpx 30rpx 0' }"
      :negative-top="600"
      show-cancel-button
      @confirm="onModConfirm"
    >
      <u-input
        v-model="score"
        border
        :clearable="false"
        placeholder="请输入分数"
      />
    </u-modal>

    <u-modal
      v-model="showQuitModal"
      content="你确定要鸽子咩？？？"
      title="鸽子来了"
      show-cancel-button="true"
      @confirm="quitActivity"
      :async-close="true"
    ></u-modal>
  </view>
</template>

<script lang="ts">
/**
 * 首页
 * @author michealZ
 */
import { Component, Mixins } from "vue-property-decorator";
import { loginMixin, utilMixin } from "@/mixins";
import { Season } from "@/types/season";

// 不能这么引入组件😑
// 编译出来的json文件路径会按照声明的路径来，就找不到了
// import { Logo } from '@/components';

@Component({
  components: {},
})
export default class extends Mixins(loginMixin, utilMixin) {
  private data = {} as any;

  private joined = false;

  private showMod = false;

  public showQuitModal = false;

  private score = "";

  private opIndex = 0;

  async onLoad(param?: any | {}) {
    console.log("detail page onload, param:", param);

    // 判断是否已登录
    let userInfo = wx.getStorageSync("user-info");

    if (!userInfo) {
      wx.redirectTo({
        url: "/pages/auth/index",
      });
    }

    if (!param.id) {
      // 用本地的数据
      this.data = this.$$store.activity;

      this.data.users.sort((prev: any, next: any) => {
        return next.score - prev.score;
      });

      this.checkJoined();
    } else {
      this.getDetail(param.id);
    }
  }

  // 分享配置
  onShareAppMessage() {
    return {
      title: this.data.name,
      path: `/pages/detail/index?id=${this.data._id}&from=${this.userInfo.id}`,
    };
  }

  get userInfo() {
    return this.$$store.userInfo;
  }

  // 计算总金额差额
  get offset() {
    let offset = 0;

    if (this.data.joiners && this.data.joiners.length) {
      offset = this.data.joiners.reduce((prev: any, { score, quit }: any) => {
        return prev + Number(quit ? 0 : score);
      }, 0);
    }

    return offset;
  }

  // 计算水钱
  get bonus() {
    let bonus = 0;

    if (this.data.joiners && this.data.joiners.length) {
      bonus = this.data.joiners.reduce((prev: any, next: any) => {
        return prev + (next.score > 0 ? next.score : 0);
      }, 0);
    }

    return (bonus / 10).toFixed(2);
  }

  private getSeasonId(season: Season[], activityId: string): string {
    let id = "";
    season.forEach((item: any) => {
      if (item.activityIds.indexOf(activityId) > -1) {
        id = item._id;
      }
    });
    return id;
  }

  private getDetail(id?: string) {
    wx.showLoading({ title: "别急哦...", mask: true });

    // 调用云函数
    wx.cloud
      .callFunction({
        name: "get_activity_by_id",
        data: { id: id || this.data._id },
      })
      .then((res: any) => {
        wx.hideLoading();

        console.log("[云函数] [get_activity_by_id] 调用成功: ", res.result);

        this.data = res.result.activity || {};

        this.data.users.sort((prev: any, next: any) => {
          return next.score - prev.score;
        });

        this.checkJoined();
      })
      .catch((err) => {
        wx.hideLoading();

        console.error("[云函数] [get_activity_by_id] 调用失败", err);
      });
  }

  private checkJoined() {
    this.data.joiners &&
      this.data.joiners.length &&
      this.data.joiners.forEach((item: any) => {
        if (item.id === this.userInfo.id && !item.quit) {
          this.joined = true;
        }
      });
  }

  private joinActivity() {
    wx.showLoading({ title: "别急哦...", mask: true });

    // 调用云函数
    wx.cloud
      .callFunction({
        name: "join_activity",
        data: {
          userId: this.userInfo.id,
          activityId: this.data._id,
          seasonId:  this.getSeasonId(this.$$store.seasons, this.data._id),
        },
      })
      .then(() => {
        wx.hideLoading();
        this.joined = true;
        this.getDetail();
      });
  }

  // 鸽子
  public quitActivity(): void {
    wx.showLoading({ title: "别急哦...", mask: true });

    wx.cloud
      .callFunction({
        name: "quit_activity",
        data: {
          userId: this.userInfo.id,
          activityId: this.data._id,
        },
      })
      .then(() => {
        wx.hideLoading();
        this.joined = false;
        this.showQuitModal = false;
        this.getDetail();
      });
  }

  private onModConfirm() {
    console.log(this.score, this.$$store.seasons[0]._id);

    if (!this.$u.test.number(+this.score)) {
      wx.showToast({ icon: "none", title: "请输入数字" });

      return;
    }

    wx.showLoading({ title: "别急哦...", mask: true });

    // 调用云函数
    wx.cloud
      .callFunction({
        name: "modify_score",
        data: {
          activityId: this.data._id,
          userId: this.userInfo.id,
          seasonId: this.getSeasonId(this.$$store.seasons, this.data._id),
          score: +this.score,
        },
      })
      .then(() => {
        wx.hideLoading();

        console.log("[云函数] [modify_score] 调用成功: ");

        // this.data.users[this.opIndex].score = +this.score;
        this.getDetail();
      })
      .catch((err) => {
        wx.hideLoading();

        wx.showModal({
          title: "提示",
          content: err,
          showCancel: false,
          confirmText: "请截图后确认",
        });

        console.error("[云函数] [modify_score] 调用失败", err);
      });
  }
}
</script>

<style lang="stylus" scoped>
.detail-wrap
  min-height 100vh
  padding 30rpx
  background #fff
  box-sizing border-box

  .title
    font-size 40rpx
    color #333
    font-weight bold

  .time
    margin 30rpx 0 40rpx
    line-height 1
    color #999

  .creator
    display flex
    align-items center

    img
      width 40rpx
      height 40rpx
      border-radius 100rpx
      margin-right 16rpx

    .creator-name
      flex 1
      margin-right: 80rpx;
      white-space nowrap
      overflow hidden
      text-overflow ellipsis
      color #666

  .user-list-tip
    padding-top 50rpx
    margin 50rpx 0 20rpx
    font-size 36rpx
    color #333
    font-weight bold
    border-top 1px solid #f1f1f1

  .counter
    display flex
    justify-content space-between
    padding 30rpx 10rpx
    color #999
    font-weight bold

  .empty-wrap
    margin-top 200rpx

  .user-list
    .user-item
      position relative
      display flex
      align-items center
      margin 45rpx 0

      &:nth-child(1)
        .user-rank
          background-color gold
          font-weight bold
          color #fff

      &:nth-child(2)
        .user-rank
          background-color silver
          font-weight bold
          color #fff

      .user-rank, .user-quit
        margin-right 20rpx
        width 45rpx
        height 45rpx
        color #666
        line-height 45rpx
        text-align center
        border-radius 10rpx

      .user-avatar
        margin-right 10rpx
        width 40rpx
        height 40rpx
        border-radius 100rpx

      .user-name
        flex 1
        font-size 28rpx
        color #666
        white-space nowrap
        overflow hidden
        text-overflow ellipsis

      .user-score
        width 70rpx
        margin 0 60rpx 0
        font-size 28rpx
        color #333
        text-align right
        font-weight bold

        &.high
          color orangered
        &.low
          color green

      .socre-mod
        position absolute
        right 0

        img
          width 35rpx
          height 30rpx
          display block
</style>
